import {
  postReportdatasetTestTransform,
  postReportdatasetExecuteDataSet
} from '@/api/dateSet'
// import {Message} from "element-ui";
import {afterFunStr, funEval} from "@/utils/FunUtil";


export async function dealAfterHandle(res, handleStr) {
  if (!handleStr) {
    return res
  }
  if (handleStr.trim() === afterFunStr.trim()) {
    return res
  }

  const fn = funEval(handleStr)
  const rtn = await fn(res)
  return rtn
}

export async function getDataJson(cptDataForm, otherParam) {
  let resStr = '{}'; // 防止JSON解析报错
  let iptStr = cptDataForm.dataText;
  if (cptDataForm.dataSource === 1) {
    resStr = JSON.parse(iptStr);
  } else if (cptDataForm.dataSource === 2) {// sql
    const dataSourceId = cptDataForm.dataSourceId
    const sql = cptDataForm.sql

    const res = await postReportdatasetTestTransform({
      dataSetParamDtoList: otherParam,
      dynSentence: sql,
      setType: 'sql',
      sourceId: dataSourceId
    })

    const rtn = await dealAfterHandle(res, cptDataForm.dataHandle)
    return rtn

  } else if (cptDataForm.dataSource === 3) { // 数据集
    const dataSetId = cptDataForm.dataSetId
    const res = await postReportdatasetExecuteDataSet({
      id: dataSetId,
      dataSetParamDtoList: otherParam
    })

    const rtn = await dealAfterHandle(res, cptDataForm.dataHandle)
    return rtn
  }
  return resStr;
}

let cptTimer = {}

export function pollingRefresh(uuid, cptDataForm, loadData) {
  if (uuid) {
    clearInterval(cptTimer[uuid]);//清除旧的定时器
  }
  if (!cptDataForm) {
    console.error("cptDataForm==>null");
    return;
  }
  if (!loadData) {
    console.error("子组件未实现数据解析方法");
    return;
  }
  loadData();
  if (cptDataForm.pollTime && cptDataForm.pollTime !== 0) {//轮询
    cptTimer[uuid] = setInterval(function () {
      loadData();
    }, cptDataForm.pollTime * 1000)
  }
}

export function clearCptInterval(uuid, clearAll) {
  if (uuid) {
    clearInterval(cptTimer[uuid]);//清除旧的定时器
  }
  if (clearAll) {
    for (const key in cptTimer) {
      clearInterval(cptTimer[key]);
    }
  }
}
